import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:flutter/material.dart';
import 'package:flutter_camera_ml_vision/flutter_camera_ml_vision.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String qrText = "";
  final _scanKey = GlobalKey<CameraMlVisionState>();
  BarcodeDetector detector = FirebaseVision.instance.barcodeDetector();
  bool scan = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: [
          RaisedButton(onPressed: () {
            setState(() {
              scan = !scan;
            });
            if (scan) {
              detector = FirebaseVision.instance.barcodeDetector();
            }
            if (!scan && detector != null) {
              detector.close();
            }
          }),
          if (scan)
            CameraMlVision<List<Barcode>>(
              key: _scanKey,
              detector: detector.detectInImage,
              resolution: ResolutionPreset.high,
              onResult: (barcodes) {
                if (barcodes == null || barcodes.isEmpty || !mounted) {
                  return;
                }
                setState(() {
                  qrText = barcodes.first.displayValue;
                  scan = false;
                });
                detector.close();
              },
              onDispose: () {
                if (detector != null) detector.close();
              },
            ),
          Text(qrText),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
